package com.czy.owner.ui.message;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.czy.otherlib.swipetoloadlayout.OnLoadMoreListener;
import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.MessageGroupAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.MainActivity;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/5/20 0020.
 */
public class GroupFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.nsv_message_group_tips)
    NestedScrollView nsvNoneTips;
    @BindView(R.id.ll_message_group_wrapper)
    LinearLayout llWrapper;

    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;

    @BindView(R.id.refresh_target)
    RecyclerView recyclerView;
    private MessageGroupAdapter mAdapter;
    private List<EMGroup> dataList = new ArrayList<>();


    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message_group;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        /*AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(500);
        set.addAnimation(animation);

        animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(100);
        set.addAnimation(animation);
        LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);*/

        nsvNoneTips.setVisibility(View.GONE);
        //dataList = getData();

        /*mAdapter.setOnItemDeleteListener(new BaseRecyclerAdapter.OnItemDeleteListener<EMGroup>() {
            @Override
            public void onItemDelete(int position, EMGroup o, View view) {
                dataList.remove(position);
                 Toast.makeText(getContext(), "OnDelete:" + mg.getTitle()+"|"+position, Toast.LENGTH_SHORT).show();
                    new ParticleSystem(getActivity(), 100, R.drawable.star_pink, 500)
                            .setSpeedRange(0.1f, 0.25f)
                                    //.setRotationSpeedRange(90, 180)
                                    //.setAcceleration(0.0001f, 90)
                            .setScaleRange(0.7f, 1.0f)
                            .oneShot(view, 100);
            }
        });*/
        //swipeToLoadLayout.setRefreshEnabled(false);
        //swipeToLoadLayout.setLoadingMore(false);
        //setListMarginBottom();
        swipeToLoadLayout.setOnRefreshListener(this);
        registerBroadcastReceiver();
    }

    /* 调整RecyclerView与底部的距离,防页面内容被TAB遮挡 */
    private void setListMarginBottom() {
        /*Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.main_tab_bottom_bg);
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        layoutParam.bottomMargin = height;
        llWrapper.setLayoutParams(layoutParam);*/
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /*swipeToLoadLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeToLoadLayout.setRefreshing(true);
            }
        });*/
    }

    private List<EMGroup> getData() {
        return EMClient.getInstance().groupManager().getAllGroups();
    }

    @Override
    public void onResume() {
        refresh();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        /*if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
        if (swipeToLoadLayout.isLoadingMore()) {
            swipeToLoadLayout.setLoadingMore(false);
        }*/
    }

    @Override
    public void onLoadMore() {
        Log.i(TAG, "onLoadMore");
    }

    @Override
    public void onRefresh() {
        MessageHelper.getInstance().setIsSyncingGroupsWithServer(false);
        MessageHelper.getInstance().asyncFetchGroupsFromServer(new EMCallBack() {
            @Override
            public void onSuccess() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                });
            }

            @Override
            public void onError(int i, String s) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "远程获取失败!",Toast.LENGTH_SHORT).show();
                        refresh();
                    }
                });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    private void refresh() {
        dataList = getData();
        swipeToLoadLayout.setRefreshing(false);
        mAdapter = new MessageGroupAdapter(getContext(), dataList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);

        recyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        checkTips();
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<EMGroup>() {
            @Override
            public void onItemClick(int position, EMGroup o, View view) {
                Intent intent = new Intent(getContext(), ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, o.getGroupId());
                startActivityForResult(intent, 0);
            }
        });
        /*mAdapter.setOnItemLongClickListener(new BaseRecyclerAdapter.OnItemLongClickListener<EMGroup>() {
            @Override
            public boolean onItemLongClick(int position, EMGroup o, View view) {
                Toast.makeText(getContext(), "OnLongClick" + o.getGroupName(), Toast.LENGTH_SHORT).show();
                return false;
            }
        });*/
    }

    private void checkTips() {
        if (mAdapter.getItemCount() > 0) {
            nsvNoneTips.setVisibility(View.GONE);
        } else {
            nsvNoneTips.setVisibility(View.VISIBLE);
        }
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_GROUP_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(Constants.ACTION_GROUP_CHANAGED)) {
                    if (EaseCommonUtils.getTopActivity(getContext()).equals(MainActivity.class.getName())) {
                        onResume();
                    }
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterBroadcastReceiver();
    }
}
